<?php

namespace App\Http\Controllers\Api;

use App\Dao\SettingDao;
use App\Exceptions\ApiErrorException;
use App\Models\Address;
use App\Models\Banners;
use App\Models\CollectionShops;
use App\Models\CollectionGoods;
use App\Models\Exchanges;
use App\Models\GoodComments;
use App\Models\Messages;
use App\Models\Orders;
use App\Models\Shopcomment;
use App\Models\Fcomments;
use App\Models\ShopRule;
use App\Models\Shops;
use App\Models\Goods;
use App\Models\Videos;
use App\Models\VideoComments;
use App\Models\Acategory;
use App\Models\Buys;
use App\Models\Users;
use App\Models\Forums;
use App\Models\Rules;
use App\Models\Signs;
use App\Models\Feedbacks;
use App\Models\Setting;
use Illuminate\Support\Facades\Cache;
use GatewayWorker\Lib\Gateway AS GatewayLib;
use DB;
use Illuminate\Support\Facades\Auth;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Dao\UploadedFileDao;
use Illuminate\Support\Str;
use PhpOffice\PhpSpreadsheet\Calculation\Category;

class HomeController extends Controller
{

    public function __construct()
    {
        parent::_init();

    }


    /**
     *  获取轮播图
     * api get_banner
     * get
     * @apiParams type =1首页   2：积分商城 3：求购专区 4：新品推荐 5：精品厂家 6：视频专区7：论坛
     * @apiSuccessExample {json} 返回值
     * {"status":1,"data":'',"msg":""}
     * */
    public function get_banner()
    {
        $type = request('type', 1);
        $banner = Banners::where('type', $type)->get();
        foreach ($banner as $g) {
            $g['url'] = get_file_url($g['url']);
        }

        return response_json(1, $banner, 'success');
    }

    /***
     * @api getRecommendShop
     * 获取精品厂家
     * @apiParms skip
     * @apiParms take
     */
    public function getRecommendShop()
    {
        $skip = request('skip', 0);
        $take = request('take', 10);
        $query = Shops::orderBy('rank', 'desc')->orderBy('num', 'desc')->where('status', 1)->where('is_recommend', 1);

        $total = $query->count();
        $shops = $query->skip($skip)->take($take)->get();
//        foreach ($shops as $g) {
//            $g['avatar'] = get_file_url($g['avatar']);
//        }
        $data['list'] = $shops;
        $data['total'] = $total;
        return response_json(1, $data, 'success');
    }

    /**
     *  获取精品厂家
     * @api get_shop
     * get
     * @apiParams skip  条数
     * @apiParams keyword
     * @apiParams take 10
     * @apiParams{string} collection_num 店铺热度 默认是0
     * @apiParams{string} num 店铺积分 默认是0
     * @apiParams{string} all 综合 默认是0
     * @apiParams{string} sall_nums 销量 默认是0
     */
    public function get_shop()
    {
        $skip = request('skip', 0);
        $take = request('take', 10);
        $all = request('all');
        $sall_nums = request('sall_nums', 0);
        $collection_num = request('collection_num', 0);
        $is_recommend = request('is_recommend', 0);
        $num = request('num', 0);
        $query = Shops::orderBy('rank', 'desc')->orderBy('num', 'desc')->where('status', 1);
        if ($is_recommend == 1) {
            $query->where('is_recommend', 1);
        }
        $keyword = request('keyword');
        if (request('keyword')) {
            $query->where('title', 'LIKE', "%" . request('keyword') . "%");
        }
        if ($all == 0) {
            $query->orderBy('sale_nums', 'asc')->orderBy('collection_num', 'asc')->orderBy('num', 'asc');
        }
        if ($sall_nums == 0) {
            $query->orderBy('sale_nums', 'asc');
        } else {
            $query->orderBy('sale_nums', 'desc');
        }
        if ($collection_num == 0) {
            $query->orderBy('collection_num', 'asc');
        } else {
            $query->orderBy('collection_num', 'desc');
        }
        if ($num == 0) {
            $query->orderBy('num', 'asc');
        } else {
            $query->orderBy('num', 'desc');
        }
        $total = $query->count();
        $shops = $query->skip($skip)->take($take)->get();

//        $arr = Shops::where('status', 1);
//
//
//        $goods = [];
//        foreach ($shops as $g) {
//            $g['avatar'] = get_file_url($g['avatar']);
//        }
//
//        foreach ($arr as $index => $val) {
//            $total += $val['num'];
//        }
//        foreach ($shops as $val) {
//            $goods = Goods::where('shop_id', $val['id'])->where('status', 1)->skip(0)->take(3)->get();
//            foreach ($goods as $g) {
//                $g['default_img'] = json_decode($g['default_img']);
//            }
//            $val['goods'] = $goods;
//        }
        $data['list'] = $shops;
        $data['total'] = $total;
        return response_json(1, $data, 'success');
    }

    /**
     * 获取厂家申请入驻
     *
     * @return \Illuminate\Http\JsonResponse
     * @throws ApiErrorException
     *
     * @author yh 20200325
     * @api {POST} /applySettle
     * @apiGroup
     * @apiVersion 1.0.0
     * @apiParam {string} p 平台，i：IOS，a：安卓，w：Web，t：触屏或手机
     * @apiParam {string} api_token 用户登录凭证
     * @apiParam {string} title 店名
     * @apiParam {string}  avatar 联系方式
     * @apiParam {string} address 营业地址
     * @apiParam {string} password 密码
     * @apiParam {string} phone 手机号
     * @apiParam {string} zhizhao 营业执照
     * @apiSuccessExample {json} 返回值
     * {"status":1,"data":'',"msg":""}
     */
    public function applySettle()
    {
        $shops = new  Shops();
        $title = request('title');
        $avatar = request('avatar');
        if (!Auth::user()) {
            return response_json(405, '', '登录已过期，请重新登录');
        }
        $zhizhao = request('zhizhao');

        $uid = Auth::user()->uid;
        $uinfo = Users::where('uid', $uid)->first();

        $phone = request('phone');
        $password = request('password');
        $salt = Str::random(6);
        $uinfo->salt = $salt;
        $shops->phone = $phone;
        $uinfo->password = get_password($password, $salt);
        $uinfo->phone = $phone;
        $uinfo->save();
        $shops->username = $uinfo->username;
        $shop = Shops::where('uid', $uid)->first();

        if (isset($shop)) {
            return response_json(0, '', '您已经创建店铺');
        }
        if (!$title) {
            return response_json(0, '', '店铺名称不能空');
        }
        if (!$avatar) {
            return response_json(0, '', '上传头像');
        }
        $address = request('address');
        if (!$address) {
            return response_json(0, '', '请填写店铺地址');
        }
        if (!$phone) {
            return response_json(0, '', '请填写联系方式');
        }
//        if (!$zhizhao) {
//            return response_json(0, '', '请上传营业执照');
//        }

        $uinfo->save();
        $shops->title = $title;
        $shops->avatar = $avatar;
        $shops->address = $address;
        $shops->phone = request('phone');
        $shops->zhizhao = request('zhizhao');
        $shops->status = 0;
        $shops->uid = $uid;
        $shops->save();
        return response_json(1, $shops, 'success');
    }

    /**
     * @author  yh 20200329
     * @api /add_shopComment 厂家评论
     * @apiParams p :w 平台
     * @apiParams api_token
     * @apiParams comment 评论内容
     * @apiParams imgs以逗号分割多个
     * @apiParams shop_id 店铺id
     * @apiSuccessExample {json} 返回值
     * {"status":1,"data":'',"msg":""}
     */
    public function add_shopComment()
    {
        $uid = Auth::user()->uid;
        $comments = request('comment');
        $imgs = request('imgs');
        $star = request('star');
        if ($comment == '') {
            return response_json(0, '', '评论内容不能为空');
        }
//        if($imgs==''){
//            return response_json(0,  '','评论内容不能为空');
//        }
        $shop_id = request('shop_id');
        $shopComment = Shopcomment::where('uid', $uid)->where('created_at', 'like', '%' . date('Y-m-d') . '%')->value('id');
        if ($shopComment) {
            return response_json(0, '', '今天已经评论了，明天再来吧');
        }
        $uinfo = Users::where('uid', $uid)->first();
        $comment = new Shopcomment();
        $comment->shop_id = $shop_id;
        $comment->uid = $uid;
        $comment->uname = $uinfo->nickname;
        $comment->add_time = date('Y-m-d h:i:s', time());
        $comment->comment = json_encode($comments);
        $comment->star = $star;
        $comment->imgs = $imgs;
        $comment->save();
        $star = Shopcomment::where('shop_id', $shop_id)->avg('star');
        Shops::where('id', $shop_id)->update(['star' => $star]);
        Shops::where('id', $shop_id)->increment('comment_num');
        return response_json(1, '', 'success');
    }

    /**
     * @author  yh 20200330
     * @api /do_collection POST
     * @apiParams p :w 平台
     * @apiParams api_token 用户token
     * @apiParams id 店铺或者商品id
     * @apiParams type 2:商品收藏 1：店铺收藏
     * @apiSuccessExample {json} 返回值
     * {"status":1,"data":'',"msg":""}
     */
    public function do_collection()
    {
        $uid = Auth::user()->uid;
        $uinfo = Users::where('uid', $uid)->first();
        $type = request('type', 1);
        $id = request('id');
        if (!$id) {
            response_json(0, '', '请选择收藏的商品');
        }
        if ($type == 1) {
            $collections = CollectionShops::where('shop_id', $id)->where('uid', $uid)->first();
            if (isset($collections)) {
                $collections->delete();
                Shops::where('id', $id)->decrement('collection_num');

            } else {
                $collection = new CollectionShops();
                $collection->uid = $uid;
                $collection->shop_id = $id;
                $collection->username = $uinfo->username;
                $collection->save();
                Shops::where('id', $id)->increment('collection_num');

            }

            return response_json(1, '', 'success');
        }
        if ($type == 2) {
            $collections = CollectionGoods::where('good_id', $id)->where('uid', $uid)->first();

            if (isset($collections)) {
                $collections->delete();
                Goods::where('id', $id)->decrement('collection_num');

            } else {
                $collection = new CollectionGoods();
                $collection->uid = $uid;
                $collection->good_id = $id;
                $collection->username = $uinfo->username;
                $collection->save();
                Goods::where('id', $id)->increment('collection_num');
            }


            return response_json(1, '', 'success');
        }
    }

    /**
     * @author  yh 20200329
     * @api /get_shopInfo 查询是否入住状态
     * @apiParams p :w 平台
     * @apiParams api_token
     * @apiSuccessExample {json} 返回值
     * {"status":1,"data":'',"msg":""}
     */
    public function get_shopInfo()
    {
        if (!Auth::user()) {
            return response_json(405, '', '登录已过期，请重新登录');
        }
        $uid = Auth::user()->uid;
        $shops = Shops::where('uid', $uid)->first();
        if (isset($shops)) {
            return response_json(1, $shops, 'success');
        } else {
            return response_json(0, $shops, '未创建店铺');
        }
    }

    /**
     * 申请入驻规则
     * @return \Illuminate\Http\JsonResponse
     * @throws ApiErrorException
     * @api getShopRule
     * @author  yh 20200401
     * @apiParams p :w
     * @apiParams p :w
     * * @apiSuccessExample {json} 返回值
     * {"status":1,"data":'',"msg":""}
     **/
    public function getShopRule()
    {
        $rule = ShopRule::where('id', 1)->first();
        return response_json(1, $rule->content, 'success');
    }

    /**
     * 获取商品列表
     *
     * @return \Illuminate\Http\JsonResponse
     * @throws ApiErrorException
     *
     * @author yh 20200325
     * @api {POST} /get_goods 1. 用户登录
     * @apiGroup Users
     * @apiVersion 1.0.0
     * @apiParam {string} p 平台，i：IOS，a：安卓，w：Web，t：触屏或手机
     * @apiParam {string} skip 跳过条数0
     * @apiParam {string} take 页数默认是10
     * @apiParam {string} cate_id 分类id
     * @apiParam {string} keyword 关键字
     * @apiParam {string} is_recommend 是否推荐默认是1
     * @apiParam {string} shop_id 店铺id
     * @apiParam {string} good_id 商品id
     * @apiParams{string} comment 店铺热度 默认是0
     * @apiParams{string} score 店铺积分 默认是0
     * @apiParams{string} all 综合 默认是0
     * @apiParams{string} sallnum 销量 默认是0
     * @apiParams{string} ignore 销量 默认是0
     * @apiSuccessExample {json} 返回值
     * {"status":1,"data":'',"msg":""}
     */
    public function get_goods()
    {
        $skip = request('skip', 0);
        $take = request('take', 10);
        $score = request('score', 0);
        $comment = request('comment', 0);
        $all = request('all', 0);
        $sallnum = request('sallnum', 0);
        $shop_id = request('shop_id');
        $cate_id = request('cate_id', 0);
        $keyword = request('keyword', '');
        $is_recommend = request('is_recommend', 1);
        $query = Goods::where('status', 1);

        if ($shop_id) {
            $query->where('shop_id', $shop_id);
        }
        $ignore = request('ignore', 0);
        if ($ignore) {
            $query->where('id', '!=', $ignore);
        }

        if ($keyword) {
            $query->where('title', 'LIKE', "%" . $keyword . "%");
        }
        if ($cate_id && empty($keyword)) {
            $query->where('cate_id', $cate_id);
            $ignore = request('ignore');
            if ($ignore) {
                $query->where('id', '!=', $ignore);
            }


        }
        if ($is_recommend) {
            $query->where('is_recommend', $is_recommend);
        }
        $count = $query->count();
        $shops = $query->skip($skip)->take($take)->get();
        foreach ($shops as $g) {
            $img = explode(',', $g['default_img']);
            $g->type = 1;
            $g['default_img'] = $img;
        }
        $data['list'] = $shops;
        $data['total'] = $count;
        return response_json(1, $data, 'success');
    }

    /**
     * 获取商品列表
     *
     * @return \Illuminate\Http\JsonResponse
     * @throws ApiErrorException
     *
     * @author yh 20200325
     * @api {POST} /get_goods 1. 用户登录
     * @apiGroup Users
     * @apiVersion 1.0.0
     * @apiParam {string} p 平台，i：IOS，a：安卓，w：Web，t：触屏或手机
     * @apiParam {string} skip 跳过条数0
     * @apiParam {string} take 页数默认是10
     * @apiParam {string} cate_id 分类id
     * @apiParam {string} keyword 关键字
     * @apiParam {string} is_recommend 是否推荐默认是1
     * @apiParam {string} shop_id 店铺id
     * @apiParam {string} good_id 商品id
     * @apiParams{string} comment 店铺热度 默认是0
     * @apiParams{string} score 店铺积分 默认是0
     * @apiParams{string} all 综合 默认是0
     * @apiParams{string} sallnum 销量 默认是0
     * @apiParams{string} ignore 销量 默认是0
     * @apiSuccessExample {json} 返回值
     * {"status":1,"data":'',"msg":""}
     */
    public function get_Shopgood()
    {
        $skip = request('skip', 0);
        $take = request('take', 10);
        $shop_id = request('shop_id');
        $keyword = request('keyword', '');
        $query = Goods::where('shop_id', $shop_id)->where('status', 1);
        if ($keyword) {
            $query->where('title', 'LIKE', "%" . $keyword . "%");
        }
        $count = $query->count();
        $shops = $query->skip($skip)->take($take)->get();
        foreach ($shops as $g) {
            $img = explode(',', $g['default_img']);
            $g->type = 1;
            $g['default_img'] = $img;
        }
        $data['list'] = $shops;
        $data['total'] = $count;
        return response_json(1, $data, 'success');
    }

    //获取分类
    public function get_cates()
    {
        $cates = Acategory::where('is_show', 1)->get();
        return response_json(1, $cates, 'success');
    }

    //获取商品列表
    public function get_buys()
    {
        $skip = request('skip');
        $take = request('take');
        $status = request('type', 1);
        $keyword = request('keyword');
        $sort = request('sort', 'id');
        $order = request('order', 'desc');
        $query = Buys::orderBy($sort, $order);
        if (request('keyword')) {
            $query->where('title', 'LIKE', "%" . request('keyword') . "%");
        }


        $query->where('status', $status);
        $total = $query->count();
        $cates = $query->skip($skip)->take($take)->get();
        $data['list'] = $cates;
        $data['total'] = $total;
        return response_json(1, $data, 'success');
    }


    /**
     * @api  getGoodsDetail
     * 获取商品详情接口
     * @apiParams id 商品id
     * @apiParams api_token 登录后必传
     **/
    public function getGoodsDetail()
    {
        $goods = Goods::where('id', request('id'))->first();


        $is_collection = 0;
        if (request('api_token')) {
            if (!Auth::user()) {
                return response_json(405, '', '登录已过期,请重新登录');
            }
            $uid = Auth::user()->uid;
            $collection_goods = CollectionGoods::where('uid', $uid)->where('good_id', request('id'))->first();
            if ($collection_goods) {
                $is_collection = 1;
            }

        }
        Goods::where('id', request('id'))->increment('views');
        $goods['default_img'] = explode(',', $goods['default_img']);
        $goods['is_collection'] = $is_collection;
        $shop = Shops::where('id', $goods['shop_id'])->first();

        $goods['uid'] = $shop->uid;
        return response_json(1, $goods, 'success');
    }

    /**
     * 商品评论接口
     * post
     * @api /goods_commit
     * @apiParams good_id商品id
     * @apiParams content 商品评论内容
     * @apiParams api_token 用户凭证
     * @apiSuccessExample {json} 返回值
     * {"status":1,"data":'',"msg":""}
     ***/
    public function goods_commit()
    {
        if (!Auth::user()) {
            return response_json(405, '', '登录已过期，请重新登录');
        }
        $id = request('good_id');
        $uid = Auth::user()->uid;
        $content = request('content');
        if (!$content) {
            return response_json(0, '', '评论内容不能为空');
        }
        $good_id = request('good_id');
        if (!$good_id) {
            return response_json(0, '', '请选择商品');
        }
        $uinfo = Users::where('uid', $uid)->first();
        $good_comment = new GoodsComments();
        $good_comment->good_id = $good_id;
        $good_comment->status = 0;
        $good_comment->content = $content;
        $good_comment->avatar = $uinfo->avatar;
        $good_comment->nickname = $uinfo->nickname;
        $good_comment->good_id = $id;
        $good_comment->save();
        Goods::where('id', $id)->increment('comments');
        return response_json(1, '', 'success');
    }

    /**
     * 商品评论列表接口
     * post
     * @api /getGoodsComment
     * @apiParams id商品id
     * @apiParams skip 条数
     * @apiParams api_token 用户凭证
     * @apiParams take 默认是10条
     * @apiSuccessExample {json} 返回值
     * {"status":1,"data":'',"msg":""}
     ***/
    public function getGoodsComment()
    {
        $skip = request('skip', 0);
        $take = request('take', 10);
        $query = GoodComments::where('goods_id', request('id'))->where('status', 1);
        $total = $query->count();
        $goods = $query->skip($skip)->take($take)->get();

        $data['list'] = $goods;
        $data['total'] = $total;
        return response_json(1, $data, 'success');
    }

    /**
     * 商品评论列表接口
     * post
     * @api /add_goodComments
     * @apiParams id商品id
     * @apiParams content 内容
     * @apiParams order_id 订单id
     * @apiParams api_token 用户凭证
     * @apiParams imgs 多个以逗号分隔
     * @apiSuccessExample {json} 返回值
     * {"status":1,"data":'',"msg":""}
     ***/
    public function add_goodComments()
    {
        $id = request('id');
        $content = request('content');
        $imgs = request('imgs');
        $order_id = request('order_id');

        if (!$id) {
            return response_json(0, '', '请选择商品');
        }
        if (!Auth::user()) {
            return response_json(405, '', '登录已过期，请重新登录');
        }
        if ($content == '') {
            return response_json(0, '', '请填写评论内容');
        }
        if ($order_id == '') {
            return response_json(0, '', '请填写订单id');
        }
        $uid = Auth::user()->uid;
        $uinfo = Users::where('uid', $uid)->first();
        $comments = new GoodComments();
        $comments->avatar = $uinfo->avatar;
        $comments->nickname = $uinfo->nickname;
        $comments->imgs = $imgs;
        $comments->goods_id = $id;
        $comments->content = $content;
        $comments->uid = $uid;
        $comments->save();
        Orders::where('id', request('order_id'))->update(['status' => 5]);
        return response_json(1, '', 'success');
    }


    //获取店铺详情
    public function getShopsDetail()
    {

        if (request('type') == 1) {
            if (!Auth::user()) {
                return response_json(405, '', '登录已过期，请重新登录');
            }
            $uid = Auth::user()->uid;
            $goods = Shops::where('uid', $uid)->first();

            return response_json(1, $goods, 'success');
        } else {
            $goods = Shops::where('id', request('id'))->first();
        }


        Shops::where('id', request('id'))->increment('num');
        if (Auth::user()) {
            $uid = Auth::user()->uid;
            $collection = CollectionShops::where('shop_id', request('id'))->where('uid', $uid)->first();
            if ($collection) {
                $goods['is_like'] = 1;
            } else {
                $goods['is_like'] = 0;
            }
        } else {

            $goods['is_like'] = 0;
        }
        return response_json(1, $goods, 'success');
    }

    /**
     *  论坛新增
     * @apiParams api_token
     * @apiParams title 论坛标题
     * @apiParams des 论坛详情
     * @apiParams id id：0 新增，编辑带对应id
     * @apiSuccessExample {json} 返回值
     * {"status":1,"data":'',"msg":""}
     */
    public function save_forums()
    {
        if (!Auth::user()) {
            return response_json(405, '', '登录已过期，请重新登录');
        }
        $uid = Auth::user()->uid;
        $uinfo = Users::where('uid', $uid)->first();
        $forums = Forums::findOrNew(request('id', 0));
        $forums->title = request('title');
        $forums->des = request('des');
        $forums->status = 0;
        $forums->avatar = $uinfo->avatar;
        $forums->nickname = $uinfo->nickname;
        $forums->uid = $uid;
        $forums->save();
        return response_json(1, '', 'success');
    }

    //获取谈论专区
    public function get_forums()
    {
        $skip = request('skip', 0);
        $take = request('take', 10);
//        当时第一页取出浏览量最多的前三项，再过滤掉
        $query = Forums::orderBy('views', 'desc');
        $keyword = request('keyword', '');
        if ($keyword) {
            $query->where('title', 'LIKE', "%" . $keyword . "%");
        }
        $total = $query->where('status', '1')->count();
        $arr = $query->where('status', '1')->skip(0)->take(3)->get();
        $query2 = Forums::where('status', '1');
        if ($keyword) {
            $query2->where('title', 'LIKE', "%" . $keyword . "%");
        }
        $arrs = [];
        $data = [];
        foreach ($arr as $g) {
            $arrs[] = $g->id;
            $data[] = $g;
        }

        if ($skip == 0) {
            $query2->whereNotIn('id', $arrs)->orderBy('created_at', 'desc');
            $total2 = $query2->count();
            $datas['total'] = intval($total) + intval($total2);
            $data2 = $query2->skip($skip)->take($take - 3)->get();
            foreach ($data2 as $g) {
                $data[] = $g;
            }
            $datas['list'] = $data;
        } else {
            $query2->whereNotIn('id', $arrs)->orderBy('created_at', 'desc');
            $datas['total'] = $query2->count();
            $data = $query2->skip($skip)->take($take)->get();
            $datas['list'] = $data;
        }
        return response_json(1, $datas, 'success');
    }

    /**
     * @ 论坛详情接口
     * @api get_ForumsDetail
     * get
     * @ author yh 20200331
     * @api_token 用户token
     * @apiParams p :w 平台
     * @apiParams content 评论内容
     * @apiParams 论坛id
     * @apiSuccessExample {json} 返回值
     * {"status":1,"data":'',"msg":""}
     */
    public function get_ForumsDetail()
    {

        $data = Forums::where('id', request('id'))->first();
        Forums::where('id', request('id'))->increment('views');


        return response_json(1, $data, 'success');
    }

    /**
     * @ 论坛评论接口
     * @api getComments
     * get
     * @ author yh 20200331
     * @api_token 用户token
     * @apiParams p :w 平台
     * @apiParams skip 分页条 默认0
     * @apiParams take 条数 默认10
     * @apiParams 论坛id
     * @apiSuccessExample {json} 返回值
     * {"status":1,"data":'',"msg":""}
     */
    public function getForumsComments()
    {
        $id = request('id');
        $skip = request('skip', 0);
        $take = request('take', 10);
        $query = Fcomments::orderBy('created_at', 'desc')->where('status', 1)->where('forums_id', request('id'));
        $total = $query->count();
        $list = $query->skip($skip)->take($take)->get();
        $data['list'] = $list;
        $data['total'] = $total;
        return response_json(1, $data, 'success');
    }

    /**
     * @ 论坛评论接口
     * @api sendComment
     * POST
     * @ author yh 20200331
     * @api_token 用户token
     * @apiParams p :w 平台
     * @apiParams content 评论内容
     * @apiParams 论坛id
     * @apiSuccessExample {json} 返回值
     * {"status":1,"data":'',"msg":""}
     */
    public function sendComment()
    {
        $id = request('id');
        $content = request('content');
        if (!Auth::user()) {
            return response_json(405, '', '登录已过期，请重新登录');
        }
        $uid = Auth::user()->uid;
        $uinfo = Users::where('uid', $uid)->first();
        $fcomments = new Fcomments();
        $froum = Forums::where('id', request('id'))->first();
        $data['forums_id'] = $id;
        $fcomments->forums_id = $id;
        $fcomments->uid = $id;
        $fcomments->nickname = $uinfo->nickname;
        $fcomments->nickname = $uinfo->nickname;
        $fcomments->avatar = $uinfo->avatar;
        $fcomments->title = $froum->title;
        $fcomments->content = $content;
        $fcomments->status = 1;
        Forums::where('id', request('id'))->increment('comment_num');
        $fcomments->save();
        return response_json(1, [], "");
    }

    //获取视频列表接口
    public function get_Videos()
    {
        $skip = request('skip', 0);
        $take = request('take', 10);

        $data = Videos::orderBy('created_at', 'desc')->where('status', '1')->skip($skip)->take($take)->get();

        $total = Videos::where('status', 1)->count();
        $datas['total'] = $total;
        $datas['list'] = $data;
        return response_json(1, $datas, 'success');
    }

    /**
     * 视频新增
     *
     * @return \Illuminate\Http\JsonResponse
     * @throws ApiErrorException
     *
     * @author yh 20200325
     * @api {POST} /web/add_video 1. 用户登录
     * @apiGroup Users
     * @apiVersion 1.0.0
     * @apiParam {string} p 平台，i：IOS，a：安卓，w：Web，t：触屏或手机
     * @apiParam {string} api_token 用户登录凭证
     * @apiParam {string} img 视频封面地址
     * @apiParam {string} title 视频标题
     * @apiParam {string} url 视频地址
     * @apiParam {string} id 新增id为0
     * @apiSuccessExample {json} 返回值
     * {"status":1,"data":'',"msg":""}
     */
    public function add_video()
    {
        if (!Auth::user()) {
            return response_json(405, '', '登录已过期，请重新登录');
        }
        $uid = Auth::user()->uid;
        $this->validate([
            'img' => 'required|',
            'url' => 'required|',
            'title' => 'required|'
        ]);
        $title = request('title');
        $uinfo = Users::where('uid', $uid)->first();
        $videos = Videos::findOrNew(request('id', 0));
        $videos->title = $title;
        $videos->img = request('img');
        $videos->url = request('url');
        $videos->author = $uinfo->nickname;
        $videos->avatar = $uinfo->avatar;
        $videos->nickname = $uinfo->nickname;
        $videos->phone = $uinfo->phone;
        $videos->author_id = $uid;
        $videos->status = 0;
        $videos->save();
        return response_json(1, $videos, 'success');
    }

    /**
     * 视频详情接口
     *
     * @return \Illuminate\Http\JsonResponse
     * @throws ApiErrorException
     *
     * @author yh 20200325
     * @api {get} /api/get_videoDetail 1. 用户登录
     * @apiGroup Users
     * @apiVersion 1.0.0
     * @apiParam {string} p 平台，i：IOS，a：安卓，w：Web，t：触屏或手机
     * @apiParam {string} id 视频地址
     * @apiSuccessExample {json} 返回值
     * {"status":1,"data":'',"msg":""}
     */
    public function get_videoDetail()
    {
        $id = request('id');
        $videos = Videos::where('id', $id)->first();
        Videos::where('id', $id)->increment('views');
        return response_json(1, $videos, 'success');
    }
    /**
     * 获取openId
     *
     * @return \Illuminate\Http\JsonResponse
     * @throws ApiErrorException
     *
     * @author yh 20200327
     * @api {POST} /web/add_video 1. 用户登录
     * @apiGroup Users
     * @apiVersion 1.0.0
     * @apiParam {string} p 平台，i：IOS，a：安卓，w：Web，t：触屏或手机
     * @apiParam {string} api_token 用户登录凭证
     * @apiParam {string} img 视频封面地址
     * @apiParam {string} title 视频标题
     * @apiParam {string} url 视频地址
     * @apiSuccessExample {json} 返回值
     * {"status":1,"data":'',"msg":""}
     */
    //获取openId
    private $app_id = 'wx56fbc12fc943c67f';
    private $app_secret = 'a7e17f0e7564428b63546e6616e2d832';

    public function get_openid()
    {
        $code = request('code');
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid={$this->app_id}&secret={$this->app_secret}&js_code={$code}&grant_type=authorization_code";
        $res = file_get_contents($url);
        return response_json(1, $res, 'success');
    }

    public function access_token()
    {
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$this->app_id}&secret={$this->app_secret}";
        $res = json_decode(file_get_contents($url));

        $access_token = $res->access_token;
        return response_json(1, $access_token, 'success');
    }

    /**
     * 检测发送内容是否合法接口
     * @apiParams  content 检查内容
     */
    public function checkMsg()
    {
        $content = request('content', '');
        function curl_post_weixin($url, $data)
        {
            if ($url && count($data)) {
                $headers = ['Content-Type:application/json'];
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); // 关键点
                curl_setopt($ch, CURLOPT_URL, $url);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                curl_setopt($ch, CURLOPT_POST, 1);
                curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
                $res = curl_exec($ch);
                curl_close($ch);
                return $res;
            }
        }

        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$this->app_id}&secret={$this->app_secret}";
        $res = json_decode(file_get_contents($url));

        $access_token = $res->access_token;
        $url = 'https://api.weixin.qq.com/wxa/msg_sec_check?access_token=' . $access_token;
        // 请求参数
        $request = [];
        $request['content'] = $content;
        $result = curl_post_weixin($url, $request);
        return $result;
    }
    /**
     * 检测发送内容是否合法接口
     * @apiParams  content 检查内容
     */
    public function check_text()
    {
        $content = request('content', '');
        function curl_post_weixin($url, $data)
        {
            if ($url && count($data)) {
                $headers = ['Content-Type:application/json'];
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); // 关键点
                curl_setopt($ch, CURLOPT_URL, $url);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                curl_setopt($ch, CURLOPT_POST, 1);
                curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data,JSON_UNESCAPED_UNICODE));
                $res = curl_exec($ch);
                curl_close($ch);
                return $res;
            }
        }

        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$this->app_id}&secret={$this->app_secret}";
        $res = json_decode(file_get_contents($url));

        $access_token = $res->access_token;
        $url = 'https://api.weixin.qq.com/wxa/msg_sec_check?access_token=' . $access_token;
        // 请求参数
        $request = [];
        $request['content'] = $content;
        $result = curl_post_weixin($url, $request);
        return $result;
    }
    /**
     * 检测发送图片是否合法
     * @apiParams  content 检查内容
     */
    public function check_msg()
    {
        function http_request($url, $data = null)

        {

            $curl = curl_init();

            //curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: multipart/form-data'));

            curl_setopt($curl, CURLOPT_URL, $url);

            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);

            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);


            if (!empty($data)) {

                curl_setopt($curl, CURLOPT_POST, TRUE);

                curl_setopt($curl, CURLOPT_POSTFIELDS, $data);

            }

            curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);

            $output = curl_exec($curl);

            curl_close($curl);

            return $output;

        }

        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$this->app_id}&secret={$this->app_secret}";
        $res = json_decode(file_get_contents($url));
        $files = request()->file('file');

        $ext = $files->getClientOriginalExtension();//文件扩展名

        $file_name = date("YmdHis", time()) . uniqid() . "." . $ext;//保存的文件名
        if (!in_array($ext, ['jpg', 'jpeg', 'gif', 'png', 'mp4', 'mp3'])) return response_json(0, '', '文件类型不支持');
        //把临时文件移动到指定的位置，并重命名
        $path = public_path() . DIRECTORY_SEPARATOR . 'uploadfiles' . DIRECTORY_SEPARATOR . 'wx' . DIRECTORY_SEPARATOR . date('Y') . DIRECTORY_SEPARATOR . date('m') . DIRECTORY_SEPARATOR . date('d') . DIRECTORY_SEPARATOR;
        $bool = $files->move($path, $file_name);


        $img_path = '/uploadfiles/wx/' . date('Y') . '/' . date('m') . '/' . date('d') . '/' . $file_name;
        $file['media'] = new \CURLFile(realpath($img_path));
        $access_token = $res->access_token;

        $url = "https://api.weixin.qq.com/wxa/img_sec_check?access_token=" . $access_token;

        $info = http_request($url, $file);
        $output = json_decode($info, true);
        if ($output['errorcode'] != 0) {
            return response_json(0, '', '图片不符合内容记录，请更换图片');
        } else {
            $data = get_file_url($img_path);
            return response_json(1, $data, 'success');
        }

    }

    /***
     * 检测音频
     * @api check_audio
     */
    public function check_media()
    {
        function http_request($url, $data = null)

        {

            $curl = curl_init();

            //curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: multipart/form-data'));

            curl_setopt($curl, CURLOPT_URL, $url);

            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);

            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);


            if (!empty($data)) {

                curl_setopt($curl, CURLOPT_POST, TRUE);

                curl_setopt($curl, CURLOPT_POSTFIELDS, $data);

            }

            curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);

            $output = curl_exec($curl);

            curl_close($curl);

            return $output;

        }

        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$this->app_id}&secret={$this->app_secret}";
        $res = json_decode(file_get_contents($url));
        $files = request()->file('file');

        $ext = $files->getClientOriginalExtension();//文件扩展名

        $file_name = date("YmdHis", time()) . uniqid() . "." . $ext;//保存的文件名
        if (!in_array($ext, ['jpg', 'jpeg', 'gif', 'png', 'mp4', 'mp3'])) return response_json(0, '', '文件类型不支持');
        //把临时文件移动到指定的位置，并重命名
        $path = public_path() . DIRECTORY_SEPARATOR . 'uploadfiles' . DIRECTORY_SEPARATOR . 'wx' . DIRECTORY_SEPARATOR . date('Y') . DIRECTORY_SEPARATOR . date('m') . DIRECTORY_SEPARATOR . date('d') . DIRECTORY_SEPARATOR;
        $bool = $files->move($path, $file_name);


        $img_path = '/uploadfiles/wx/' . date('Y') . '/' . date('m') . '/' . date('d') . '/' . $file_name;
        $data = get_file_url($img_path);
        return response_json(1, $data, 'success');

        $file['media_url'] = $data ;
        $file['media_type'] = 1;
        $access_token = $res->access_token;

        $url = "https://api.weixin.qq.com/wxa/api.weixin.qq.com/wxa/media_check_async?access_token=" . $access_token;

        $info = http_request($url, $file);
        $output = json_decode($info, true);
        if ($output['errorcode'] != 0) {
            return response_json(0, '', '音频不符合要求，请重试');
        } else {
            return response_json(1, $data, 'success');
        }
    }

    /**
     * cURL方式POST数据到微信
     * @param string $url 请求地址
     * @param array $data 发送数据
     * @return resource
     */
    public
    function getQrcode()
    {

        function curl_post_weixin($url, $data)
        {
            if ($url && count($data)) {
                $headers = ['Content-Type:application/json'];
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); // 关键点
                curl_setopt($ch, CURLOPT_URL, $url);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                curl_setopt($ch, CURLOPT_POST, 1);
                curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
                $res = curl_exec($ch);
                curl_close($ch);
                return $res;
            }
        }

        if (!Auth::user()) {
            return response_json(405, '', '登录已过期，请重新登录');
        }

        $uid = Auth::user()->uid;
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$this->app_id}&secret={$this->app_secret}";
        $res = json_decode(file_get_contents($url));
        $access_token = $res->access_token;


        $url = 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=' . $access_token;
        // 请求参数
        $request = [];
        $request['scene'] = $uid;
        $request['page'] = 'pages/auth/index'; // 扫码跳转页面
        $request['width'] = 280; //小程序大小设置 px
        $request['is_hyaline'] = TRUE; //是否需要透明底色
        // 从微信端请求数据
        $result = curl_post_weixin($url, $request);
        $path = public_path() . DIRECTORY_SEPARATOR . 'uploadfiles' . DIRECTORY_SEPARATOR . 'wx' . DIRECTORY_SEPARATOR . date('Y') . DIRECTORY_SEPARATOR . date('m') . DIRECTORY_SEPARATOR . date('d') . DIRECTORY_SEPARATOR;
        $fileName = date("YmdHis", time()) . uniqid() . ".png";
        file_put_contents($path . '/' . $fileName, $result);

        $img_path = '/uploadfiles/wx/' . date('Y') . '/' . date('m') . '/' . date('d') . '/' . $fileName;
        $data = get_file_url($img_path);

        return response_json(1, $data, 'success');

    }

    /**
     * 获取openId
     *
     * @author yh 20200327
     * @api {get} /get_rule 1. 用户登录
     * @apiGroup Users
     * @apiVersion 1.0.0
     * @apiParam {string} p 平台，i：IOS，a：安卓，w：Web，t：触屏或手机
     * @apiParam {string} api_token 用户登录凭证 登录后必传
     * @apiSuccessExample {json} 返回值
     * {"status":1,"data":'',"msg":""}
     */
    public
    function get_rule()
    {
        $rule = Rules::first();
        $api_token = request('api_token');
        $count = 0;
        if ($api_token != '') {
            if (!Auth::user()) {
                return response_json(405, '', '登录已过期，请重新登录');
            }
            $uid = Auth::user()->uid;
            $uinfo = Users::where('uid', $uid)->first();
            $count = $uinfo->score;
        }
        $rule->count = $count;
        $rule->now = date('Y-m-d H:i:s', time());
        return response_json(1, $rule, 'success');
    }

    public
    function get_sign()
    {
        if (!Auth::user()) {
            return response_json(405, '', '登录已过期，请重新登录');
        }
        $uid = Auth::user()->uid;

        $skip = request('skip', 0);
        $take = request('take', 10);
        $signs = Signs::orderBy('created_at', 'desc')->where('uid', $uid)->skip($skip)->take($take)->get();
        $total = Signs::where('uid', $uid)->count();
        $data['list'] = $signs;
        $data['total'] = $total;
        return response_json(1, $data, 'success');
    }

    public
    function do_sign()
    {
        if (!Auth::user()) {
            return response_json(405, '', '登录已过期，请重新登录');
        }
        $uid = Auth::user()->uid;
        $sings = Signs::where('uid', $uid)->where('created_at', 'like', '%' . date('Y-m-d') . '%')->value('id');
        if ($sings) {
            return response_json(0, '', '您已经签到了，明天再来吧');
        }

        $uinfo = Users::where('uid', $uid)->first();
        $rule = Rules::first();

        $uinfo->score = $uinfo['score'] + $rule['score'];
        $uinfo->save();
        $signs = new Signs();
        $signs->uid = $uid;
        $signs->scores = $rule->score;
        $signs->username = $uinfo->username;
        $signs->save();
        return response_json(1, '', 'success');
    }

    public
    function about()
    {
        $about = SettingDao::getSetting('setting');

        $data = $about['system_desc'];
        return response_json(1, $data, 'success');
    }

    /**
     * 上传文件
     *
     * @return \Illuminate\Http\JsonResponse
     * @throws ApiErrorException
     *
     * @author yh 20200327
     * @api {POST} /web/add_video 1. 用户登录
     * @apiGroup Users
     * @apiVersion 1.0.0
     * @apiParam {string} p 平台，i：IOS，a：安卓，w：Web，t：触屏或手机
     * @apiParam {string} api_token 用户登录凭证
     * @apiParam {string} file 文件
     * @apiParam {string} type 类型 1：图片 2：视频 3：音频
     * @apiParam {string} from 模块 1：avatar 2：视频 3：求购 4：商品
     * @apiSuccessExample {json} 返回值
     * {"status":1,"data":'',"msg":""}
     */
    public
    function uploads()
    {
        //获取文件name值
        $file = request()->file('file');
        if ($file) {
            $ext = $file->getClientOriginalExtension();//文件扩展名

            $file_name = date("YmdHis", time()) . uniqid() . "." . $ext;//保存的文件名
            if (!in_array($ext, ['jpg', 'jpeg', 'gif', 'png', 'mp4', 'mp3'])) return response_json(0, '', '文件类型不支持');
            //把临时文件移动到指定的位置，并重命名
            $path = public_path() . DIRECTORY_SEPARATOR . 'uploadfiles' . DIRECTORY_SEPARATOR . 'wx' . DIRECTORY_SEPARATOR . date('Y') . DIRECTORY_SEPARATOR . date('m') . DIRECTORY_SEPARATOR . date('d') . DIRECTORY_SEPARATOR;
            $bool = $file->move($path, $file_name);

            if ($bool) {
                $img_path = '/uploadfiles/wx/' . date('Y') . '/' . date('m') . '/' . date('d') . '/' . $file_name;
                $data = get_file_url($img_path);
                return response_json(1, $data, '上传成功');
            } else {
                return response_json(0, '', '上传失败');
            }
        } else {
            return response_json(0, '', '上传失败');
        }
    }

    /**
     * @author yh 20200329
     * @api feedback
     * @apiParam  content 意见反馈内容
     * @apiParam {string} p 平台，i：IOS，a：安卓，w：Web，t：触屏或手机
     * @apiParam {string} api_token 用户登录凭证
     **/
    public
    function feedback()
    {
        $api_token = request('api_token');
        $feedback = new Feedbacks();
        $feedback->username = '';
        $feedback->nickname = '';
        $feedback->phone = '';
        $feedback->avatar = '';
        if ($api_token) {
            if (!Auth::user()) {
                return response_json(405, '', '登录已过期，请重新登录');
            }
            $uid = Auth::user()->uid;
            $uinfo = Users::where('uid', $uid)->first();
            $feedback->username = $uinfo->username;
            $feedback->nickname = $uinfo->nickname;
            $feedback->avatar = get_file_url($uinfo['avatar']);
            $feedback->phone = $uinfo->phone;
        }

        $feedback->content = request('content');
        $feedback->save();
        return response_json(1, '', 'message');
    }

    /**
     * @ 我的收藏列表
     * @api get_favor
     * @ author yh 20200331
     * @api_token 用户token
     * @apiParams p :w 平台
     * @apiparams keyword 关键字
     * @apiparams skip 页码
     * @apiparams take 页数 10
     * @apiSuccessExample {json} 返回值
     * {"status":1,"data":'',"msg":""}
     */
    public
    function get_favor()
    {
        if (!Auth::user()) {
            return response_json(405, '', '登录已过期，请重新登录');
        }
        $uid = Auth::user()->uid;
        $keyword = request('keyword');
        $skip = request('skip', 0);
        $take = request('take', 10);
        $query = CollectionGoods::where('uid', $uid);
        if ($keyword != '') {

            $query->join('goods', function ($join) {
                $join->on('goods.id', '=', 'collection_goods.good_id')->where('goods.title', 'LIKE', "%" . request('keyword') . "%");
            });

        }
        $collectionS = $query->skip($skip)->take($take)->get();
        foreach ($collectionS as $g) {
            $goods = Goods::where('id', $g['good_id'])->first();

            $img = explode(',', $goods['default_img']);


            $goods['default_img'] = $img;
            $g['good'] = $goods;
        }
        $total = CollectionGoods::where('uid', $uid)->count();
        $data['total'] = $total;
        $data['list'] = $collectionS;
        return response_json(1, $data, 'message');
    }

    /**
     * @ 我的关注厂家
     * @api get_collectionShop
     * @ author yh 20200331
     * @api_token 用户token
     * @apiPrams keyword
     * @apiParams p :w 平台
     * @apiSuccessExample {json} 返回值
     * {"status":1,"data":'',"msg":""}
     */
    public
    function get_collectionShop()
    {
        if (!Auth::user()) {
            return response_json(405, '', '登录已过期，请重新登录');
        }
        $skip = request('skip', 0);
        $take = request('take', 10);
        $uid = Auth::user()->uid;
        $keyword = request('keyword');
        $query = CollectionShops::where('collection_shops.uid', $uid);
        if ($keyword != '') {
            $query->join('shops', function ($join) {
                $join->on('shops.id', '=', 'collection_shops.shop_id')->where('shops.title', 'LIKE', "%" . request('keyword') . "%");
            });

        }
        $total = $query->count();
        $collectionS = $query->skip($skip)->take($take)->get();

        $total = CollectionShops::where('collection_shops.uid', $uid)->count();
        $data['total'] = $total;
        $data['list'] = $collectionS;
        return response_json(1, $data, 'message');
    }

    /**
     * @ 我的求购列表
     * @api my_buy
     * @ author yh 20200331
     * @api_token 用户token
     * @apiParams p :w 平台
     * @apiParams skip 0条数
     * @apiParams take每页条数 默认是10
     * @apiParams status默认4 1进行中 3已完成 2审核失败
     * @apiSuccessExample {json} 返回值
     * {"status":1,"data":'',"msg":""}
     */
    public
    function my_buy()
    {
        $status = request('status', 4);
        if (!Auth::user()) {
            return response_json(405, '', '登录已过期，请重新登录');
        }
        $uid = Auth::user()->uid;

        $skip = request('skip', 0);
        $keyword = request('keyword');
        $take = request('take', 10);
        $sort = request('sort', 'created_at');
        $order = request('order', 'desc');
        $query = Buys::orderBy($sort, $order);
        $query->where('author_id', $uid);
        $total = Buys::where('author_id', $uid)->count();
        if ($keyword) {
            $query->where('title', 'LIKE', "%" . request('keyword') . "%");
        }
        if ($status != 4) {
            $query->where('status', $status)->select();
            $total = Buys::where('author_id', $uid)->where('status', $status)->count();
        }

        $collectionS = $query->skip($skip)->take($take)->get();
        $data['total'] = $total;
        $data['list'] = $collectionS;
        return response_json(1, $data, 'message');
    }

    /**
     * @ 求购列表
     * @api buys
     * @ author yh 20200331
     * @apiParams p :w 平台
     * @apiParams skip 0条数
     * @apiParams take每页条数 默认是10
     * @apiParams keyword 关键字
     * @apiParams status
     * @apiSuccessExample {json} 返回值
     * {"status":1,"data":'',"msg":""}
     */
    public
    function buys()
    {

        $skip = request('skip', 0);
        $take = request('take', 10);
        $keyword = request('keyword', '');
        $collectionS = Buys::where('status', 1)->where('title', 'LIKE', "%" . $keyword . "%")->skip($skip)->take($take)->get();
        $data['total'] = Buys::where('status', 1)->count();
        $data['list'] = $collectionS;
        return response_json(1, $data, 'message');
    }

    /**
     *  求购详情接口
     * @api get
     * @api getBuyDetail
     * @apiParams id 求购id
     * @apiSuccessExample {json} 返回值
     * {"status":1,"data":'',"msg":""}
     */
    public
    function getBuyDetail()
    {
        $buys = Buys::where('id', request('id'))->first();
        return response_json(1, $buys, 'success');
    }

    /**
     * @ 求购新增
     * @api save_buy
     * post
     * @ author yh 20200331
     * @api_token 用户token
     * @apiParams p :w 平台
     * @apiParams title 求购标题
     * @apiParams des 求购简介
     * @apiParams remark 求购备注 非必填
     * @apiParams need_nums 求购数量
     * @apiParams size 求购规格型号
     * @apiParams endDate 截至日期 yyyy-mm-dd hh:mm：ss
     * @apiParams id
     * @apiSuccessExample {json} 返回值
     * {"status":1,"data":'',"msg":""}
     */
    public
    function save_buy()
    {
        if (!Auth::user()) {
            return response_json(405, '', '登录已过期，请重新登录');
        }
        $uid = Auth::user()->uid;

        $title = request('title');
        if (!$title) {
            return response_json(0, '', '求购标题不能为空');
        }

        $des = request('des');
        if (!$des) {
            return response_json(0, '', '求购描述不能为空');
        }
        $remark = request('remark');
        $size = request('size');
        if (!$size) {
            return response_json(0, '', '请填写求购规格');
        }
        $need_nums = request('need_nums');
        if (!$need_nums) {
            return response_json(0, '', '请填写求购数量');
        }
        $endDate = request('endDate');
        if (!$endDate) {
            return response_json(0, '', '请填写求购截至时间');
        }
        $phone = request('phone');
        if (!$phone) {
            return response_json(0, '', '请填写联系方式');
        }
        $uinfo = Users::where('uid', $uid)->first();
        $id = request('id', 0);
        $buy = Buys::findOrNew($id);
        $buy->title = $title;
        $buy->des = $des;
        $buy->remark = $remark;
        $buy->size = $size;
        $buy->need_nums = $need_nums;
        $buy->endDate = $endDate;
        $buy->author = $uinfo->username;
        $buy->nickname = $uinfo->nickname;
        $buy->avatar = $uinfo->avatar;
        $buy->author_id = $uinfo->uid;
        $buy->status = 0;
        $buy->phone = $phone;
        $buy->save();
        return response_json(1, $buy, 'message');
    }

    /**
     * @ 积分商城
     * @api get_exchanges
     * get
     * @ author yh 20200331
     * @apiVersion 1.0.0
     * @apiParam {string} p 平台，i：IOS，a：安卓，w：Web，t：触屏或手机
     * @apiParam {string} api_token 用户登录凭证
     * @apiParam {string} skip 跳过条数0
     * @apiParam {string} take 页数默认是10
     * @apiParam {string} cate_id 分类id
     * @apiParam {string} keyword 关键字
     * @apiParam {string} is_recommend 是否推荐默认是1
     * @apiParam {string} shop_id 店铺id
     * @apiParams{string} comment 店铺热度 默认是0
     * @apiParams{string} score 店铺积分 默认是0
     * @apiParams{string} all 综合 默认是0
     * @apiParams{string} sallnum 销量 默认是0
     * @apiSuccessExample {json} 返回值
     * {"status":1,"data":'',"msg":""}
     */
    public
    function get_exchanges()
    {
        $skip = request('skip', 0);
        $take = request('take', 10);
        $score = request('score', 0);
        $comment = request('comment', 0);
        $all = request('all', 0);
        $sale_num = request('sallnum', 0);
        $shop_id = request('shop_id');
        $cate_id = request('cate_id');
        $keyword = request('keyword', '');
        $st = 'and status = 1';
        if ($cate_id) {
            $st = $st . ' and cate_id=' . $cate_id;
        }
        if ($shop_id) {
            $st = $st . ' and shop_id= ' . $shop_id;
        }
        $orderBy = '';
        if ($all == 1) {
            $orderBy = 'score,exchange_nums,sale_nums';
        } else {
            $orderBy = '';
            if ($score == 1) {
                $orderBy = $orderBy . 'score, ';
            } else {
                $orderBy = $orderBy . 'score DESC ,';
            }
            if ($comment == 1) {
                $orderBy = $orderBy . ' exchange_nums,';
            } else {
                $orderBy = $orderBy . ' exchange_nums DESC, ';
            }
            if ($sale_num == 1) {
                $orderBy = $orderBy . ' sale_nums';

            } else {
                $orderBy = $orderBy . ' sale_nums DESC';
            }
        }
        $total = DB::select('SELECT  COUNT(*) as total FROM hd_exchanges  WHERE title  LIKE \'%' . $keyword . '%\'' . $st . ' ORDER BY ' . $orderBy);
        $tr = 'SELECT * FROM hd_exchanges  WHERE title  LIKE \'%' . $keyword . '%\'' . $st . ' ORDER BY ' . $orderBy . '   LIMIT  ' . $skip . ', ' . $take;

        $shops = DB::select($tr);
        if (is_object($shops)) {
            $shops = (array)($shops);
        } else {
            $shops = $shops;
        }
        foreach ($shops as $g) {
            if ($g->type == 1) {
                $arr = [];
                $goods = Goods::where('id', $g->good_id)->first();
                $img = explode(',', $goods->default_img);

                $g->default_img = $img;
                $shop = Shops::where('id', $g->shop_id)->first();
                $g->shop_name = $shop->title;
                $g->address = $shop->address;
            } else {
                $img = explode(',', $g->img);

                $g->default_img = $img;

            }
        }
        $data['list'] = $shops;
        $data['total'] = $total[0]->total;
        return response_json(1, $data, 'success');
    }

    /**
     * @api add_address 添加地址
     * post
     * @author  yh 20200331
     * @apiParams p :w 平台
     * @apiParams api_token 用户登录凭证
     * @apiParams province 省
     * @apiParams province_code 省id
     * @apiParams city 市
     * @apiParams city_code 市
     * @apiParams county_code 县城
     * @apiParams county 县城
     * @apiParams address 详细地址
     * @apiParams username 姓名
     * @apiParams  phone  手机号
     * @apiParams id 编辑传id
     */
    public
    function add_address()
    {
        $id = request('id');
        $address = Address::findOrNew($id);
        $username = request('username');
        $phone = request('phone');
        $province = request('province');
        $province_code = request('province_code');
        $city = request('city');
        $city_code = request('city_code');
        $county = request('county');
        $county_code = request('county_code');
        $address1 = request('address');

        if (!$username) {
            return response_json(0, '', '联系人不能为空');
        }
        if (!$phone) {
            return response_json(0, '', '联系人方式不能为空');
        }
        $address->username = $username;
        $address->phone = $phone;
        $address->province = $province;
        $address->address = $address1;
        $address->county = $county;
        $address->city = $city;
        $address->province_code = $province_code;
        $address->city_code = $city_code;
        $address->county_code = $county_code;
        $address->type = 0;
        $address->uid = Auth::user()->uid;
        $address->save();
        return response_json(1, '', 'message');
    }

    /**
     * 地址列表接口
     * @api get_address
     * get
     * @author  yh 20200401
     * @apiParams p :w 平台
     * @apiParams skip 页码
     * @apiParams take 页面
     * @apiParams api_token 用户登录凭证
     * @apiParams id 地址id
     */
    public
    function get_address()
    {
        if (!Auth::user()) {
            return response_json(405, '', '登录已过期，请重新登录');
        }
        $skip = request('skip', 0);
        $take = request('take', 10);
        $uid = Auth::user()->uid;
        $address = Address::orderBy('type', 'desc')->orderBy('created_at', 'desc')->where('uid', $uid)->skip($skip)->take($take)->get();
        $total = Address::where('uid', $uid)->count();
        $data['list'] = $address;
        $data['total'] = $total;
        return response_json(1, $data, 'success');
    }

    /**
     * 设置默认地址
     * @api set_address
     * post
     * @author  yh 20200401
     * @apiParams p :w 平台
     * @apiParams api_token 用户登录凭证
     * @apiParams id 地址id
     */
    public
    function set_address()
    {
        if (!Auth::user()) {
            return response_json(405, '', '登录已过期，请重新登录');
        }
        $uid = Auth::user()->uid;

        $address = Address::where('uid', $uid)->where('type', 5)->get();
        if ($address) {
            foreach ($address as $g) {
                $g['type'] = 1;
                $g->save();
            }
        }
        $address = Address::where('id', request('id'))->first();
        $address->type = 5;
        $uinfo = Users::where('uid', $uid)->first();
        $address->save();
        $uinfo->address_id = request('id');
        $uinfo->save();
        return response_json(1, '', 'success');
    }

    /**
     * 兑换商品接口
     * post
     * @author yh 20200401
     * @api exchangeShop
     * @apiParams p :w 平台
     * @apiParams exchange_id 商品id
     * @apiParams exchange_num 兑换数量
     * @apiParams address_id 兑换地址id
     * @apiParams remarks 备注
     * @apiParams size 尺寸
     * @apiParams type
     * @apiSuccessExample {json} 返回值
     * {"status":1,"data":'',"msg":""}
     */

    public
    function exchangeShop()
    {
        if (!Auth::user()) {
            return response_json(405, '', '登录已过期，请重新登录');
        }
        $uid = Auth::user()->uid;
        $exchange_id = request('exchange_id');
        $exchange_num = request('exchange_num');
        $type = request('type');
        if ($type == 2) {
            if ($exchange_num != 1) {
                return response_json(0, '', '红包只允许兑换一个哟');
            }
            $shopComment = Orders::where('exchange_id', $exchange_id)->where('type', 2)->where('exchange_uid', $uid)->where('created_at', 'like', '%' . date('Y-m-d') . '%')->value('id');
            if ($shopComment) {
                return response_json(0, '', '今天已经兑换该红包了，明天再来吧');
            }

        }
        $e = Exchanges::where('id', $exchange_id)->first();
        if ($e->author_id == $uid) {
            return response_json(0, '', '不能兑换自己店铺的商品哟,请看看别的商品吧');
        }

        function getRandomString($len, $chars = null)
        {
            if (is_null($chars)) {
                $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
            }
            mt_srand(10000000 * (double)microtime());
            for ($i = 0, $str = '', $lc = strlen($chars) - 1; $i < $len; $i++) {
                $str .= $chars[mt_rand(0, $lc)];
            }
            return $str;
        }

        if (request('address_id') == '') {
            return response_json(0, '', '请填写兑换地址');
        }


        if (!$exchange_num) return response_json(0, '', '请填写兑换数量');


        if (!isset($e)) {
            return response_json(0, '', '商品不存在或者下架，请重试');
        }
        $numbers = date('Ymd') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8) . rand(1000, 9999);;

        $exchange = new Orders();


        $uinfo = Users::where('uid', $uid)->first();
        $total = ($e->score) * $exchange_num;
        $uscore = $uinfo->score;
        $nums = $uscore - $total;
        if ($nums < 0) {
            return response_json(0, '', '您的积分不足，无法兑换');
        }
        if ($e['exchange_nums'] - $e['sale_nums'] < $exchange_num) {
            return response_json(0, '', '商品不足');
        }
        if ($type == 1) {
            $shop = Shops::where('id', $e->shop_id)->first();
            $shop->sale_nums = $shop->sale_nums + 1;
            $shop->save();

        }
        $sale_num = $e->sale_nums;

        $e->sale_nums = $sale_num + $exchange_num;
        $e->rent_nums = $e->exchange_nums - $sale_num - $exchange_num;
        if (request('type') == 1) {
            $sizes = $e->size;
            if (!empty($$sizes)) {
                $size = json_decode($sizes, true);
                $exhibit_num_json = [];
                foreach ($size as $g) {
                    if ($g['size_name'] == request('size')) {
                        $exhibit_num_json[] = [
                            'size_name' => $g['size_name'],
                            'size_num' => $g['size_num'] - $exchange_num,

                        ];

                    } else {
                        $exhibit_num_json[] = [
                            'size_name' => $g['size_name'],
                            'size_num' => $g['size_num']
                        ];
                    }
                }
                $e->size = json_encode($exhibit_num_json);
            }
            $good = Goods::where('id', $e->good_id)->first();
            $good->rent_nums = $e->exchange_nums - $sale_num - $exchange_num;
            $good->save();
        }


        $uinfo->score = $nums;
        $sign = new Signs();
        $sign->uid = $uid;
        $sign->type = 2;
        $sign->add_type = 2;
        $sign->scores = $total;
        $sign->username = $uinfo->username;
        $sign->save();
        $exchange->title = $e->title;
        $exchange->exchange_username = $uinfo->username;
        $exchange->exchange_phone = $uinfo->phone;
        $exchange->remarks = request('remarks');
        $exchange->exchange_id = $exchange_id;
        $exchange->author_id = $e->author_id;
        $exchange->code = getRandomString(6);
        $exchange->number = $numbers;
        $exchange->exchange_nums = $exchange_num;
        $exchange->shop_id = $e->shop_id;
        $exchange->good_id = $e->good_id;
        $exchange->type = $e->type;
        $exchange->size = request('size');
        $exchange->address_id = request('address_id');
        $exchange->username = $e->author;
        $exchange->phone = $e->phone;
        $exchange->exchange_uid = $uinfo->uid;
        $exchange->money = $e->money;
        $exchange->score = $e->score;
        $exchange->save();

        $e->save();
        $uinfo->save();
        return response_json(1, $exchange, 'success');
    }

    /**
     * 我的订单列表
     * post
     * @author yh 20200401
     * @api get_myorder
     * @apiParams p :w 平台
     * @apiParams api_token 用户凭证
     * @apiParams keyword 关键字
     * @apiParams status 0:全部 1:进行中，2已发货 3：待评价 4已完成
     * @apiParams skip 页码 默认0
     * @apiParams take:10,
     * @apiParams type:1用户，2商铺
     * @apiSuccessExample {json} 返回值
     * {"status":1,"data":'',"msg":""}
     */
    public
    function get_myorder()
    {
        $keyword = request('keyword');
        if (!Auth::user()) {
            return response_json(405, '', '登录已过期，请重新登录');
        }
        $uid = Auth::user()->uid;
        if (!$uid) {
            return response_json(405, '', '登录已过期，请重新登录');
        }
        $take = request('take', 10);
        $skip = request('skip', 0);
        $type = request('type', 1);
        if ($type == 2) {
            $query = Orders::where('author_id', $uid);

        } else {
            $query = Orders::where('exchange_uid', $uid);

        }


        if ($keyword) {
            $query->where('title', 'LIKE', "%" . $keyword . "%");
        }
        $status = request('status', 0);
        if ($status != 0) {
            $query->where('status', $status);
        }
        $total = $query->count();
        $arr = $query->skip($skip)->take($take)->get();
        foreach ($arr as $g) {
            if ($g['type'] == 1) {
                $g['shop'] = Shops::where('id', $g['shop_id'])->first();

                $g['good'] = Goods::where('id', $g['good_id'])->first();
                if ($g['good']) {
                    $default_img = $g['good']->default_img;
                    $img = explode(',', $default_img);
                    $g['good']->default_img = $img;
                }
            }
            if ($g['type'] == 2) {

                $exchanges = Exchanges::where('id', $g['exchange_id'])->first();
                $g['default_img'] = get_file_url($exchanges->img);
            }

        }
        $data['total'] = $total;
        $data['list'] = $arr;
        return response_json(1, $data, 'success');
    }

    /**
     * 兑换商品接口
     * get
     * @author yh 20200401
     * @api getMoneyDetail
     * @apiParams p :w 平台
     * @apiParams id 商品id
     * @apiParams api_token 用户token
     * @apiSuccessExample {json} 返回值
     * {"status":1,"data":'',"msg":""}
     */
    public
    function getMoneyDetail()
    {
        $id = request('id');
        $exchanges = Exchanges::where('id', $id)->first();
        if (!$exchanges) {
            return response_json(0, '', '该商品不存在');
        }
        if ($exchanges->type == 2) {
            $exchanges->default_img = [get_file_url($exchanges->img)];
        } else {
            $good = Goods::where('id', $exchanges->good_id)->first();
            $is_collection = 0;
            if (request('api_token')) {
                if (!Auth::user()) {
                    return response_json(405, '', '登录已过期,请重新登录');
                }
                $uid = Auth::user()->uid;
                $collection_goods = CollectionGoods::where('uid', $uid)->where('good_id', $exchanges->good_id)->first();
                if ($collection_goods) {
                    $is_collection = 1;
                }

            }
            $exchanges->content = $good->content;
            $exchanges->sizes = $exchanges->size;

            $img = explode(',', $good['default_img']);

            $exchanges->default_img = $img;
            $exchanges->is_collection = $is_collection;
        }

        return response_json(1, $exchanges, 'success');
    }

    /**
     * 确认发货
     * @api send_code
     * post
     * @apiParams p :w 平台
     * @apiParams id 订单id
     * @apiParams kd_name物流公司名
     * @apiParams kd_num物流编码
     * @apiParams api_token
     * */
    public
    function send_code()
    {
        $id = request('id');
        $order = Orders::where('id', $id);
        if (!Auth::user()) {
            return response_json(405, '', '登录已过期，请重新登录');
        }
        $uid = Auth::user()->uid;

        $kd_name = request('kd_name');
        $kd_num = request('kd_num');
        if (!$kd_name) {
            return response_json(0, '', '快递公司不能为空');
        }
        if (!$kd_num) {
            return response_json(0, '', '快递单号不能为空');
        }
        $order = Orders::where('id', $id)->first();
        $order->kd_name = $kd_name;
        $order->kd_num = $kd_num;
        $order->status = 2;
        $order->save();
        return response_json(1, $order, 'success');
    }

    /**
     * 修改发货信息
     * @api change_send
     * @apiParams p :w 平台
     * @apiParams id 订单id
     * @apiParams kd_name物流公司名
     * @apiParams kd_num物流编码
     * @apiParams api_token
     */
    public
    function change_send()
    {
        $id = request('id');
        $order = Orders::where('id', $id);
        if (!Auth::user()) {
            return response_json(405, '', '登录已过期，请重新登录');
        }
        $uid = Auth::user()->uid;

        $kd_name = request('kd_name');
        $kd_num = request('kd_num');
        if (!$kd_name) {
            return response_json(0, '', '快递公司不能为空');
        }
        if (!$kd_num) {
            return response_json(0, '', '快递单号不能为空');
        }
        $order = Orders::where('id', $id)->first();
        $order->kd_name = $kd_name;
        $order->kd_num = $kd_num;
        $order->status = 2;
        $order->save();
        return response_json(1, $order, 'success');
    }

    /**
     * 确认收货
     * @api get_orders
     * post
     * @apiParams p :w 平台
     * @apiParams id 订单id
     * @apiParams api_token
     * */
    public
    function get_orders()
    {
        if (!Auth::user()) {
            return response_json(405, '', '登录已过期，请重新登录');
        }
        $id = request('id');
        $order = Orders::where('id', $id)->first();
        $user = Users::where('uid', $order['author_id'])->first();
        $total = $user->score + ($order->exchange_num) * ($order->score);
        $user->score = $user->score + ($order->exchange_num) * ($order->score);
        $user->save();
        $sign = New Signs();
        $sign->uid = $order->author_id;
        $sign->type = $order->type;
        $sign->add_type = 1;
        $sign->scores = $total;
        $sign->username = $user->username;
        $sign->save();
        $order->status = 3;
        $order->save();
        return response_json(1, '', 'success');
    }

    /**
     * 确认兑换
     * @api exchange_code
     * post
     * @apiParams p :w 平台
     * @apiParams id 订单id
     * @apiParams api_token
     * @apiParams code
     * */
    public
    function exchange_code()
    {
        if (!Auth::user()) {
            return response_json(405, '', '登录已过期，请重新登录');
        }
        $uid = Auth::user()->uid;
        $order = Orders::where('id', request('id'))->first();
        if ($order->status == 4) {
            return response_json(0, '', '红包已经兑换完成了，无法再次兑换');
        }
        $code = request('code');
        if ($code != $order->code) {
            return response_json(0, '', '兑换码不正确');
        }

        $order->status = 4;
        $user = Users::where('uid', $uid)->first();
        $sign = New Signs();
        $sign->uid = $order->author_id;
        $total = $user->score + ($order->exchange_num) * ($order->score);
        $user->score = $total;
        $user->save();
        $sign->type = 2;
        $sign->add_type = 1;
        $sign->scores = $total;
        $sign->username = $user->username;
        $sign->save();

        $order->save();
        return response_json(1, '', 'success');
    }

    /***
     *  聊天发起
     * @api  send_message
     * post
     * @apiParams api_token
     * @apiParams fid 接受放id
     * @apiParams type 1商家,type:2 兑换商品
     * @apiParams content 消息内容
     *
     */
    public
    function send_message()
    {
        $content = request('content');
        if (!Auth::user()) {
            return response_json(405, '', '登录已过期，请重新登录');
        }
        $uid = Auth::user()->uid;

        $user = Users::where('uid', request('fid'))->first();

        $message = new Messages();
        $message->content = $content;
        $message->uid = $uid;
        $message->fid = $user->uid;
        $message->type = request('type');
        $message->save();
        return response_json(1, $message, 'success');
    }

    /**
     * 用户聊天绑定接口
     *
     * @author yyj 20180118
     *
     * @api {POST} /bind 2机器号绑定接口
     * @apiVersion 1.0.0
     * @apiParam {string} p 平台，t：小程序
     * @apiParam {string} api_token 用户token
     * @apiParam {string} client_id 链接上tcp后获得的client_id
     */
    public
    function bind()
    {
        GatewayLib::$registerAddress = env('WM_REGISTER_IP', '127.0.0.1') . ':' . env('WM_REGISTER_PORT', '1238');
        $uid = Auth::user()->uid;
        $this->validate([
            'client_id' => 'required|string|min:20',
        ]);
        $client_id = request('client_id');
        if (GatewayLib::isOnline($client_id)) {
            //判断当前机器号是否绑定过client_id
            $is_bind_arr = GatewayLib::getClientIdByUid($uid);
            if (!empty($is_bind_arr)) {
                foreach ($is_bind_arr as $g) {
                    //断开之前绑定的client_id
                    GatewayLib::closeClient($g);
                    Cache::forget($g);
                }
            }
            cache([
                $client_id => $uid
            ], Carbon::now()->addSeconds(600));
            //绑定机器号
            GatewayLib::bindUid($client_id, $uid);
        } else {
            throw new ApiErrorException('client_id无效');
        };
        return response_json(1, [], '绑定成功');
    }

    /**
     * 获取聊天消息记录
     * @api get_messageList
     * @apiParams api_token
     * @apiParams fid
     * @apiParams skip
     * @apiParams take
     * @apiSuccessExample {json} 返回值
     * {"status":1,"data":'',"msg":""}
     **/
    public
    function get_messageList()
    {
        if (!Auth::user()) {
            return response_json(405, '', '登录已过期，请重新登录');
        }
        $uid = Auth::user()->uid;
        $take = request('take', 10);
        $skip = request('skip', 0);
        $fid = request('fid');
        $messages = DB::select('SELECT * FROM hd_messages where ( uid = ' . $uid . ' AND fid =' . $fid . ') OR (uid =' . $fid . ' AND fid = ' . $uid . ') ORDER BY created_at desc LIMIT ' . $skip . ',' . $take);
//        $messages=Messages::where('uid',$uid)->where('fid',$fid)->whereOr(function ($q) use ($uid,$fid){
//            $q->where('uid',$fid)->where('fid',$uid);
//        })->orderBy('id','desc')->skip($skip)->take($take)->get()->toArray();
        Messages::where('uid', $uid)->where('fid', $fid)->update(['uread_type' => 1]);
        Messages::where('fid', $uid)->where('uid', $fid)->update(['fread_type' => 1]);
        $data['user'] = Users::where('uid', $uid)->first();
        $data['fuser'] = Users::where('uid', $fid)->first();
        $data['list'] = $messages;

        return response_json(1, $data, 'success');
    }

    /**
     *私聊列表
     * @param $inArr
     * @return \Illuminate\Http\JsonResponse
     * @api getMessage
     * get
     * @apiParams: api_token
     **
     */
    public
    function getMyMessage()
    {
        if (!Auth::user()) {
            return response_json(405, '', '登录已过期，请重新登录');
        }
        $take = request('take', 10);
        $skip = request('skip', 0);
        $uid = Auth::user()->uid;

        $total = DB::select('select COUNT(*) as total from hd_messages a where (a.fid= ' . $uid . ' and a.id in(select max(a.id) from hd_messages a where a.fid=' . $uid . ' group by a.uid))');
        $query = DB::select('select * from hd_messages a where (a.fid= ' . $uid . ' and a.id in(select max(a.id) from hd_messages a where a.fid=' . $uid . ' group by a.uid))  limit ' . $skip . ',' . $take . ';');
        if (is_object($query)) {
            $arr = (array)($query);
        } else {
            $arr = $query;
        }
        foreach ($arr as $g) {
            $messages = Messages::orderBy('created_at', 'desc')->where('uid', $g->fid)->where('fid', $g->uid)->first();

            if ($messages) {
                if ($messages->id > $g->id) {
                    $g->created_at = $messages['created_at']->format('Y-m-d H:i:s');
                    $g->content = $messages->content;
                    $g->type = $messages->type;
                }

            }
            if ($g->fid == $uid) {
                $shops = Shops::where('uid', $g->uid)->first();
                if ($shops) {
                    $g->title = $shops->title;
                    $g->avatar = $shops->avatar;

                } else {
                    $user = Users::where('uid', $g->uid)->first();
                    if(isset($user)){
                        $g->title = $user->nickname;
                        $g->avatar = get_file_url($user->avatar);
                    }

                }
                $g->fid = $g->uid;
                $g->uid = $uid;
            } else {
                $shops = Shops::where('uid', $g->fid)->first();

                if ($shops) {
                    $g->title = $shops->title;
                    $g->avatar = get_file_url($shops->avatar);
                } else {
                    $user = Users::where('uid', $g->fid)->first();
                    $g->title = $user->nickname;
                    $g->avatar = get_file_url($user->avatar);
                }
            }
            $g->count = Messages::where('fid', $uid)->where('uid', $g->fid)->where('fread_type', 0)->count();


        }
        $data['list'] = $arr;
        $data['total'] = $total[0]->total;
        return response_json(1, $data, 'success');
    }

    /***
     * 看视频获取积分
     * @api video_score
     * @author yh 20200403
     * @apiParams api_token
     * post
     * @apiParams id 视频id
     * @apiSuccessExample {json} 返回值
     * {"status":1,"data":'',"msg":""}
     */
    public
    function video_score()
    {
        if (!Auth::user()) {
            return response_json(405, '', '登录已过期，请重新登录');
        }
        $uid = Auth::user()->uid;

        $id = request('id');
        if (!$id) {
            return responce_json(0, '', '视频id不能为空');
        }
        $video = Videos::where('id', $id)->first();
        Videos::where('id', $id)->increment('times');
        Videos::where('id', $id)->increment('views');
        $score = $video->score;
        $uinfo = Users::where('uid', $uid)->first();
        $uinfo->score = $uinfo->score + $score;
        $uinfo->save();
        return response_json(1, '', '积分添加成功');
    }

    /**
     * 视频评论接口
     * @api add_videoComment
     * post
     * @apiParams api_token
     * @apiParams id 视频id
     * @apiParams content 评论内容
     * @apiSuccessExample {json} 返回值
     * {"status":1,"data":"","msg":""}
     */
    public
    function add_videoComment()
    {
        if (!Auth::user()) {
            return response_json(405, '', '登录已过期，请重新登录');
        }
        $uid = Auth::user()->uid;
        $content = request('content');
        $id = request('id');
        $video = Videos::where('id', $id)->first();

        $video_comment = new VideoComments();
        $video_comment->title = $video->title;
        $video_comment->video_id = $id;
        $video_comment->uid = $uid;
        $video_comment->content = $content;
        $video_comment->status = 1;
        $video_comment->save();
        Videos::where('id', $id)->increment('comments');
        $video->save();
        return response_json(1, '', '评论成功审核中');
    }

    /***
     *  获取视频评论接口
     * @api getVideoCommentList
     * @api get
     * @apiParams id
     * @apiParams skip
     * @apiParams take
     * @apiSuccessExample {json} 返回值
     * {"status":1,"data":"","msg":""}
     */
    public
    function getVideoCommentList()
    {
        $id = request('id', 1);
        $skip = request('skip', 0);
        $take = request('take', 10);
        $comment = VideoComments::orderBy('created_at', 'des')->where('video_id', $id)->where('status', 1)->skip($skip)->take($take)->get();
        foreach ($comment as $g) {
            $user = Users::where('uid', $g['uid'])->first();
            $g['avatar'] = $user->avatar;
            $g['nickname'] = $user->nickname;
        }
        $total = VideoComments::where('video_id', $id)->where('status', 1)->count();
        $data['total'] = $total;
        $data['list'] = $comment;
        return response_json(1, $data, 'success');
    }

    /**
     * 获取个人中心板块数据接口
     * @api getcenter
     * @apiParams api_token
     * get 请求方式
     * @apiSuccessExample {json} 返回值
     * {"status":1,"data":"","msg":""}
     */
    public
    function getCenter()
    {
        if (!Auth::user()) {
            return response_json(405, '', '登录已过期，请重新登录');
        }
        $uid = Auth::user()->uid;

        //关注店铺总数
        $data = CollectionShops::where('uid', $uid)->count();
        //收藏商品总数
        $count = CollectionGoods::where('uid', $uid)->count();
        $message = Messages::where('fid', $uid)->where('fread_type', 0)->count();
        $buyTotal = Buys::where('author_id', $uid)->count();
        $score = Users::where('uid', $uid)->first();
        $datas['shopTotal'] = $data;
        $datas['goodsTotal'] = $count;
        $datas['messageTotal'] = $message;
        $datas['buyTotal'] = $buyTotal;
        $datas['score'] = $score->score;
        return response_json(1, $datas, '');
    }

    /**
     * 获取个人未读消息
     * @api getMessageTotal
     * @apiParams api_token
     * get 请求方式
     * @apiSuccessExample {json} 返回值
     * {"status":1,"data":"","msg":""}
     */
    public
    function getMessageTotal()
    {
        if (!Auth::user()) {
            return response_json(405, '', '登录已过期，请重新登录');
        }
        $uid = Auth::user()->uid;
        $message = Messages::where('fid', $uid)->where('fread_type', 0)->count();
        $datas['messageTotal'] = $message;

        return response_json(1, $datas, '');
    }

    /**
     * 个人中心订单
     * getOrderList
     * @apiParams api_token 用户凭证
     * @apiParams p：w平台类型
     * @apiParams type=0所有 1：进行中 2：已发货3：已签收 4：已完成
     * @apiSuccessExample {json} 返回值
     * {"status":1,"data":"","msg":""}
     *
     **/
    public
    function getOrderList()
    {
        if (!Auth::user()) {
            return response_json(405, '', '登录已过期，请重新登录');
        }
        $uid = Auth::user()->uid;
        $skip = request('skip', 0);
        $take = request('take', 10);
        $order = Orders::where('uid', $uid);
        if (request('type') != 0) {
            $order->where('status', request('type'));
        }
        $ordes = $order->skip($skip)->take($take)->get();
        $data['total'] = Orders::where('uid', $uid)->count();
        $data['list'] = $ordes;
        return responce_json(1, $data, 'success');
    }

    /**
     * 获取小程序浏览量
     * get
     * @api getTotal
     * * @apiSuccessExample {json} 返回值
     * {"status":1,"data":"","msg":""}
     */
    public
    function getTotal()
    {
        ShopRule::increment('total');
        $rule = ShopRule::where('id', 1)->first();
        $total = $rule->total;
        return response_json(1, $total, 'success');
    }

    /**
     * 商家后台登录接口
     * get
     * @api login
     * @api phone
     * @api password
     * @api phone
     * @apiSuccessExample {json} 返回值
     *
     * {"status":1,"data":"","msg":""}
     */
    public
    function login()
    {
        $phone = request('phone');
        $shops = Shops::where('phone', $phone)->first();
        if (!$shops) {
            return response_json(0, '', '您未创建店铺，请先创建店铺再来吧');
        }
        $username = Users::where('phone', $phone)->first();
        if ($username) {
            if (get_password(request('password'), $username->salt) != $username->password) {
                return response_json(0, '', '用户名或密码错误');
            }
            $username->api_token = get_api_token($username->uid);
            $username->save();
            return response_json(1, [
                'uid' => $username->uid,
                'api_token' => $username->api_token
            ]);
        } else {
            return response_json(0, '', '用户不存在，请重试');
        }

    }

    /**
     * 店铺信息修改接口
     * @api shop_edit
     * @api post
     * @author  yh 20200408
     * @apiParams api_token
     * @apiParams title
     * @apiParams des
     * @apiParams avatar
     * @apiParams zhizhao
     * @apiParams address
     * @apiParams phone
     * @apiParams password
     *
     **/
    public
    function shop_edit()
    {
        if (!Auth::user()) {
            return response_json(405, '', '登录已过期，请重新登录');
        }
        $uid = Auth::user()->uid;
        $user = Users::where('uid', $uid)->first();
        $id = request('id');
        if (!$id) {
            $shops = Shops::where('uid', $uid)->first();
        } else {
            $shops = Shops::findOrNew($id);
        }
        $shops->title = request('title');
        $shops->des = request('des');
        $shops->avatar = request('avatar');
        $shops->zhizhao = request('zhizhao');
        $shops->address = request('address');
        $shops->username = $user->username;
        $shops->phone = request('phone');
        $shops->status = 0;
        $user = Users::where('phone', request('phone'))->first();
        if ($user) {
            if ($user->uid != $uid) {
                return response_json(0, '', '该手机已存在，请更换');
            }
        } else {
            $user = Users::where('uid', $uid)->first();
            $user->phone = request('phone');
        }
        $shops->save();
        $user->save();
        return response_json(1, '', 'success');
    }

    /**
     * 店家商品获取
     * @api get_shopGood
     * @api get
     * @author  yh 20200411
     * @apiParams api_token
     * @apiParams keyword 搜索关键字
     * @apiParams skip 页数
     * @apiParams take 页码
     **/
    public
    function get_shopGoods()
    {
        $keyword = request('keyword');
        $skip = request('skip', 0);
        $take = request('take', 10);
        if (!Auth::user()) {
            return response_json(405, '', '登录已过期，请重新登录');
        }
        $uid = Auth::user()->uid;
        $shop_id = Shops::where('uid', $uid)->first();
        $query = Goods::orderBy('created_at', 'desc')->where('shop_id', $shop_id->id);
        if ($keyword) {
            $query->where('title', 'LIKE', "%" . $keyword . "%");
        }
        $goods = $query->skip($skip)->take($take)->get();
        foreach ($goods as $g) {

            $img = explode(',', $g['default_img']);

            $g['default_img'] = $img;
        }
        $data['total'] = Goods::where('shop_id', $shop_id->id)->count();
        $data['list'] = $goods;
        return response_json(1, $data, 'success');
    }

    /***
     *   求购完成状态修改
     * @api post do_finish
     * @apiParams api_token
     * @apiParams id 求购id,
     * @author yh 20200428
     */
    public
    function do_finish()
    {
        if (!Auth::user()) {
            return response_json(405, '', '登录已过期，请重新登录');
        }
        $id = request('id');
        if (!$id) {
            return response_json(0, '', '请选择求购完成的id');
        }
        $uid = Auth::user()->uid;
        $buys = Buys::where('id', $id)->where('author_id', $uid)->first();
        $buys->status = 3;
        $buys->save();
        return response_json(1, '', 'success');
    }

    /***
     *  删除接口
     * @apiParams do_delete
     * @apiParams type 1商品 2讨论 3视频4,求购
     * @apiParams id
     */
    public
    function do_delete()
    {
        $type = request('type', 1);
        $id = request('id');
        if ($type == 1) {
            // 判断用户是否可以被删
            Exchanges::where('good_id', $id)->delete();
            CollectionGoods::where('good_id', $id)->delete();
            Goods::where('id', $id)->delete();
        }
        if ($type == 2) {
            Forums::destroy($id);
            Fcomments::where('forums_id', $id)->delete();

        }
        if ($type == 3) {
            Videos::destroy($id);
            VideoComments::where('video_id', $id)->delete();

        }
        if ($type == 4) {
            Buys::destroy($id);
        }
        return response_json(1, '', 'success');
    }

    /***
     *
     * 商品新增或者编辑接口
     * @api goods_save
     * @api post
     * @apiParams api_token
     * @apiParams id 编辑时传商品id,非编辑传0
     * @apiParams title 商品标题
     * @apiParams sign 商品标签，多个以逗号分割
     * @apiParams address 商品地址
     * @apiParams cate_id 商品id
     * @apiParams sizes
     * @apiParams send_type 是否包邮 1包邮0不包邮
     * @apiParams content 内容
     * @apiParams total 商品总数
     * @apiParams default_img 主图
     */
    public
    function goods_save()
    {
        if (!Auth::user()) {
            return response_json(405, '', '登录已过期，请重新登录');
        }
        DB::transaction(function () {
            $uid = Auth::user()->uid;
            $user = Goods::findOrNew(request('id'));
            $user->title = request('title');
            $shops = Shops::where('uid', $uid)->first();

            $shops = Shops::where('id', $shops->id)->first();
            $user->shop_name = $shops->title;
            $user->sign = request('sign');
            $default_img = request('default_img');
            $user->shop_id = $shops->id;
            $user->cate_id = request('cate_id');
            $user->address = request('address');;
            $user->send_type = request('send_type');
            $user->default_img = $default_img;
            $user->content = request('content');
            $user->sizes = request('sizes');
            $user->total = request('total');
            $user->save();
        });
        return response_json(1, '', 'success');
    }

    /**
     * 商家视频列表获取
     * video_lists
     * @api get
     * @author  yh 20200411
     * @apiParams api_token
     * @apiParams keyword 搜索关键字
     * @apiParams skip 页数
     * @apiParams take 页码
     */
    public
    function video_lists()
    {
        $keyword = request('keyword');
        $skip = request('skip', 0);
        $take = request('take', 10);
        if (!Auth::user()) {
            return response_json(405, '', '登录已过期，请重新登录');
        }
        $uid = Auth::user()->uid;

        $query = Videos::orderBy('created_at', 'desc')->where('author_id', $uid);
        if ($keyword) {
            $query->where('title', 'LIKE', "%" . $keyword . "%");
        }
        $goods = $query->skip($skip)->take($take)->get();
        $total = Videos::where('author_id', $uid)->count();
        $data['total'] = $total;
        $data['list'] = $goods;
        return response_json(1, $data, 'success');
    }

    /***
     *
     * 视频新增或者编辑接口
     * @api save_video
     * @api post
     * @apiParams api_token
     * @apiParams id 编辑时传商品id,非编辑传0
     * @apiParams title 视频id
     * @apiParams img 视频封面
     * @apiParams url 视频地址
     */
    public
    function save_video()
    {
        if (!Auth::user()) {
            return response_json(405, '', '登录已过期，请重新登录');
        }
        $uid = Auth::user()->uid;
        $this->validate([
            'img' => 'required|',
            'url' => 'required|',
            'title' => 'required|'
        ]);
        $title = request('title');
        $uinfo = Users::where('uid', $uid)->first();
        $videos = Videos::findOrNew(request('id'));
        $videos->title = $title;
        $videos->img = request('img');
        $videos->url = request('url');
        $videos->author = $uinfo->nickname;
        $videos->avatar = $uinfo->avatar;
        $videos->nickname = $uinfo->nickname;
        $videos->phone = $uinfo->phone;
        $videos->author_id = $uid;
        $videos->status = 0;
        $videos->save();
        return response_json(1, $videos, 'success');
    }

    /**
     * 商品下架或者上架
     *api post change
     * @apiParams api_token
     * @apiParams p =w
     * @apiParams id
     * @author lxp 20160713
     */
    public
    function change()
    {
        $id = request('id');
        $goods = Goods::where('id', $id)->first();
        if ($goods->status == 2) {
            $goods->status = 1;
        } else {
            $goods->status = 2;
        }
        $goods->save();
        return response_json(1, '', 'success');
    }

    /***
     * 兑换详情接口
     * 获取订单详情接口
     * @api getOrderDetail
     * @api get
     * @apiParams api_token
     * @apiParams id
     * @apiParams type:1 商品 2：红包
     *
     */
    public
    function getOrderDetail()
    {
        if (!Auth::user()) {
            return response_json(405, '', '登录已过期，请重新登录');
        }
        $type = request('type', 1);
        $uid = Auth::user()->uid;
        $orders = Orders::where('id', request('id'))->first();
        if ($type == 1) {
            $shops = Shops::where('id', $orders->shop_id)->first();

            $good = Goods::where('id', $orders->good_id)->first();
            $img = explode(',', $good['default_img']);
            $good['default_img'] = $img;
            $orders->good = $good;
            $orders->shop = $shops;
        }
        $orders->address = Address::where('id', $orders->address_id)->first();

        return response_json(1, $orders, 'success');
    }

    /***
     * 获取入驻最新数据
     * @api getNews
     * @apiParams p 平台类型
     * @apiParams take 条数
     * @apiParams skip 条数
     */
    public
    function getNews()
    {
        $shops = Shops::orderBy('created_at', 'desc')->where('status', 1)->get();
        return response_json(1, $shops, 'success');
    }

    /***
     * 获取论坛管理接口
     * @api get getUserFrums
     * @apiParams api_token
     * @apiParams p w 平台类型
     * @apiParams take 条数
     * @apiParams skip 条数
     */
    public
    function getUserFrums()
    {
        if (!Auth::user()) {
            return response_json(405, '', '登录已过期，请重新登录');
        }
        $skip = request('skip', 0);
        $take = request('take', 10);
        $keyword = request('keyword');
        $uid = Auth::user()->uid;
        $query = Forums::orderBy('created_at', 'desc')->where('uid', $uid);
        if ($keyword) {
            $query->where('title', 'LIKE', "%" . $keyword . "%");
        }
        $total = $query->count();
        $lists = $query->skip($skip)->take($take)->get();
        $data['total'] = $total;
        $data['list'] = $lists;
        return response_json(1, $data, 'success');
    }
}
